<template>
  <view class="uni-padding-wrap">
    <view class="uni-title">提交表单</view>
    <view class="form-hint">带<span class="required">*</span>号的为必填项</view>
    <form @submit="submitForm">
      <!-- 时间 -->
      <view class="form-section">
        <view class="form-row">
          <view class="form-column">
            <view><span class="required">*</span>入住日期</view>
            <picker mode="date" :value="formData.checkInDate" @change="bindCheckInDateChange">
              <view class="picker-text">{{ formData.checkInDate || '请选择入住日期' }}</view>
            </picker>
            <view v-if="checkInDateError" class="error-message">请选择入住日期</view>
          </view>
          <view class="form-column">
            <view><span class="required">*</span>退房日期</view>
            <picker disabled="true" mode="date" :value="formData.checkOutDate" @change="bindCheckOutDateChange">
              <view class="picker-text">{{ formData.checkOutDate || '请选择退房日期' }}</view>
            </picker>
            <view v-if="checkOutDateError" class="error-message">请选择退房日期</view>
          </view>
        </view>
        <view class="form-row">
          <view class="form-column">
            <view><span class="required">*</span>常住人数</view>
            <picker mode="selector" :range="residentCountOptions" @change="bindResidentCountChange">
              <view class="picker-text">{{ formData.residentCount || '请选择常住人数' }}</view>
            </picker>
            <view v-if="residentCountError" class="error-message">请选择常住人数</view>
          </view>
        </view>
      </view>

      <!-- 姓名 -->
      <view class="uni-form-item">
        <view class="form-item">
          <view class="title"><span class="required">*</span>姓 名：</view>
          <input class="input-field" v-model="formData.name" placeholder="请输入姓名" />
        </view>
        <view v-if="nameError" class="error-message">请输入姓名</view>
      </view>

      <!-- 性别选择 -->
      <view class="uni-form-item">
        <view class="form-item">
          <view class="title"><span class="required">*</span>性 别：</view>
          <radio-group @change="radioChange">
            <label>
              <radio value="男" :checked="formData.gender==='男'" />男
            </label>
            <view style="width: 20px;"></view> <!-- 增加间距 -->
            <label>
              <radio value="女" :checked="formData.gender==='女'" />女
            </label>
          </radio-group>
        </view>
        <view v-if="genderError" class="error-message">请选择性别</view>
      </view>

      <!-- 手机号 -->
      <view class="uni-form-item">
        <view class="form-item">
          <view class="title"><span class="required">*</span>手 机 号：</view>
          <input class="input-field" v-model="formData.phone" placeholder="请输入手机号" @input="checkPhone" />
        </view>
        <view v-if="phoneError" class="error-message">手机号格式不正确</view>
      </view>

      <!-- 身份证号 -->
      <view class="uni-form-item">
        <view class="form-item">
          <view class="title"><span class="required">*</span>身份证号：</view>
          <input class="input-field" v-model="formData.idNumber" placeholder="请输入身份证号" @input="checkIdNumber" />
        </view>
        <view v-if="idNumberError" class="error-message">身份证号码格式不正确</view>
      </view>

      <!-- 身份证复印件上传 -->
      <view class="uni-form-item">
        <view class="form-item">
          <view class="title">身份证复印件：</view>
          <view v-if="!formData.idCopy.length" class="upload-link" @click="chooseImage">点击上传图片</view>
          <view v-if="formData.idCopy.length" class="image-preview">
            <image v-for="(item, index) in formData.idCopy" :src="item" :key="index" @click="previewImage(item)" />
            <view class="add-link" @click="chooseImage">+ 继续上传</view>
          </view>
        </view>
        <view v-if="idCopyError" class="error-message">请上传身份证复印件</view>
      </view>

      <!-- 申请原因 -->
      <view class="uni-form-item">
        <view class="form-item">
          <view class="title"><span class="required">*</span>申请原因：</view>
          <textarea class="textarea-field" v-model="formData.reason" placeholder="请输入申请原因" />
        </view>
        <view v-if="reasonError" class="error-message">请输入申请原因</view>
      </view>

      <!-- 提交按钮 -->
      <button form-type="submit" type="primary">下一步</button>
    </form>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        formData: {
          name: '',
          gender: "男",
          phone: '',
          idNumber: '',
          idCopy: [],
          reason: '',
          checkInDate: '',
          checkOutDate: '',
          residentCount: ''
        },
        phoneError: false,
        idNumberError: false,
        nameError: false,
        genderError: false,
        reasonError: false,
        checkInDateError: false,
        checkOutDateError: false,
        residentCountError: false,
        idCopyError: false,
        residentCountOptions: [1, 2, 3, 4, 5, 6]
      };
    },
    onShow() {
      this.loadUserInfo();
    },
    watch: {
      formData: {
        handler(newVal) {
          uni.setStorageSync('formData', newVal);
        },
        deep: true
      }
    },
    methods: {
      loadUserInfo() {
        const storedFormData = uni.getStorageSync('formData');
        if (storedFormData) {
          this.formData = storedFormData;
        } else {
          const userInfo = uni.getStorageSync('userInfo');
          if (userInfo) {
            this.formData = {
              ...this.formData,
              ...userInfo
            };
            uni.setStorageSync('formData', this.formData);
          }
        }
      },
      radioChange(e) {
        this.formData.gender = e.detail.value;
        this.genderError = false;
      },
      chooseImage() {
        uni.chooseImage({
          count: 1,
          success: (res) => {
            this.formData.idCopy = this.formData.idCopy.concat(res.tempFilePaths);
            this.idCopyError = false;
          }
        });
      },
      previewImage(currentImage) {
        uni.previewImage({
          current: currentImage,
          urls: this.formData.idCopy
        });
      },
      checkPhone() {
        this.phoneError = !/^1[3-9]\d{9}$/.test(this.formData.phone) && this.formData.phone.length > 0;
      },
      checkIdNumber() {
        this.idNumberError = !/^[1-9]\d{5}(18|19|20)?\d{2}(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])\d{3}(\d|X)?$/
          .test(this.formData.idNumber) && this.formData.idNumber.length > 0;
      },
      bindCheckInDateChange(e) {
        this.formData.checkInDate = e.detail.value;
        this.checkInDateError = false;
      },
      bindCheckInDateChange(e) {
        this.formData.checkInDate = e.detail.value;
        this.checkInDateError = false;

        // 将入住日期加一年设置为退房日期
        const checkInDate = new Date(this.formData.checkInDate);
        const checkOutDate = new Date(checkInDate.setFullYear(checkInDate.getFullYear() + 1));
        this.formData.checkOutDate = checkOutDate.toISOString().split('T')[0]; // 转换为 YYYY-MM-DD 格式
      },
      bindResidentCountChange(e) {
        this.formData.residentCount = this.residentCountOptions[e.detail.value];
        this.residentCountError = false;
      },
      submitForm(e) {
        e.preventDefault();
        this.checkPhone();
        this.checkIdNumber();

        // 校验必填项
        this.nameError = !this.formData.name;
        this.genderError = !this.formData.gender;
        this.reasonError = !this.formData.reason;
        this.checkInDateError = !this.formData.checkInDate;
        this.checkOutDateError = !this.formData.checkOutDate;
        this.residentCountError = !this.formData.residentCount;
        this.idCopyError = !this.formData.idCopy.length;

        if (
          this.nameError ||
          this.genderError ||
          this.reasonError ||
          this.checkInDateError ||
          this.checkOutDateError ||
          this.residentCountError ||
          this.phoneError ||
          this.idNumberError ||
          this.idCopyError
        ) {
          uni.showToast({
            title: '请填写完整信息',
            icon: 'none'
          });
          return;
        }

        uni.showModal({
          title: '确认信息',
          content: '请确认填写的信息无误',
          confirmText: '确认',
          cancelText: '继续修改',
          success: (res) => {
            if (res.confirm) {
              this.formData.idCopy.forEach(file => {
                uni.uploadFile({
                  url: '你的上传图片接口地址',
                  filePath: file,
                  name: 'file',
                  success: (res) => console.log(res.data),
                  fail: (err) => console.error('上传失败', err)
                });
              });

              uni.showToast({
                title: '提交成功',
                icon: 'success',
                success: () => uni.navigateTo({
                  url: '/myDormitory/myDormitory/myDormitory'
                })
              });
            }
          }
        });
      }
    }
  };
</script>

<style>
  .uni-padding-wrap {
    padding: 15px;
    font-size: 15px;
  }

  .uni-title {
    text-align: center;
    font-weight: bold;
    margin-bottom: 20px;
  }

  .form-hint {
    color: #888;
    margin-bottom: 10px;
  }

  .form-section {
    border: 3px solid #2BA245;
    border-radius: 10px;
    margin-bottom: 20px;
  }

  .form-row {
    display: flex;
  }

  .form-column {
    flex: 50%;
    border: 3px solid #2BA245;
    padding: 10rpx;
    display: flex;
    flex-direction: column;
  }

  .form-item {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
  }

  .title {
    font-weight: bold;
    min-width: 90px;
    margin-right: 10px;
  }

  .required {
    color: red;
  }

  .input-field,
  .textarea-field {
    flex: 1;
    border: 1px solid #ccc;
    border-radius: 4px;
    padding: 0 12px;
    height: 40px;
    box-sizing: border-box;
    font-size: 15px;
  }

  .textarea-field {
    height: 100px;
    padding: 12px;
  }

  .error-message {
    color: red;
    font-size: 12px;
    margin-top: 4px;
  }

  .picker-text {
    height: 100rpx;
    display: flex;
    align-items: center;
    color: #888;
  }

  button {
    background-color: #2ba100;
    color: white;
    border: none;
    border-radius: 4px;
    padding: 12px 20px;
    font-size: 15px;
    width: 100%;
    margin-top: 20px;
  }

  .upload-link,
  .add-link {
    color: #2ba245;
    text-decoration: underline;
    cursor: pointer;
  }

  .image-preview {
    display: flex;
    align-items: center;
  }

  .image-preview image {
    width: 100px;
    height: 100px;
    margin-right: 10px;
    margin-bottom: 10px;
  }

  radio-group {
    display: flex;
    align-items: center;
  }

  radio {
    margin-right: 10px;
  }
</style>